package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.entity.User;
import com.demo.mapper.PermissionMapper;
import com.demo.mapper.UserMapper;
import com.demo.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    /*
        让security框架调用这个方法，走自定义的认证流程
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户消息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getLoginAct, username));
        if (StringUtils.isEmpty(user)){
            System.out.println("用户名或密码有误");
            throw new UsernameNotFoundException("用户名或密码有误");
        }

        // 根据用户标识查询用户的权限标识符集合
        Set<String> permissionLIst = permissionMapper.selectPermissionListByUserId(user.getId());


        Collection<? extends GrantedAuthority>authorities = Collections.emptyList();
        // 创建自己的认证用户消息
        SecurityUser userDetails = SecurityUser.builder()
                .id(user.getId())
                .loginAct(user.getLoginAct())
                .loginPwd(user.getLoginPwd())
                .name(user.getName())
                .phone(user.getPhone())
                .email(user.getEmail())
                .createTime(user.getCreateTime())
                .lastLoginTime(user.getLastLoginTime())
                .authorities(authorities) // 权限消息
                .accountNoLocked(user.getAccountNoLocked()) // 用户未锁定
                .accountNoExpired(user.getAccountNoExpired()) // 账号未过期
                .accountEnabled(user.getAccountEnabled())
                .enabled(true)
                .permissionLIst(permissionLIst)
                .build();
        System.out.println(userDetails.toString());
        return userDetails;
    }
}
